<template>
  <div class="data-table-container">
    <!-- 表格工具栏 -->
    <div class="table-toolbar" v-if="config?.showToolbar !== false">
      <!-- 搜索框 -->
      <div class="search-section" v-if="config?.showSearch !== false">
        <el-input
          v-model="searchText"
          :placeholder="config?.searchPlaceholder || '请输入搜索内容'"
          :style="{ width: config?.searchWidth || '300px' }"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 筛选条件 -->
      <div class="filter-section" v-if="config?.filters && config.filters.length > 0">
        <el-select
          v-for="filter in config.filters"
          :key="filter.prop"
          v-model="filterValues[filter.prop]"
          :placeholder="filter.placeholder || `请选择${filter.label}`"
          :style="{ width: filter.width || '150px', marginLeft: '10px' }"
          clearable
          @change="handleFilter"
        >
          <el-option
            v-for="option in filter.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-section" v-if="config?.actions && config.actions.length > 0">
        <el-button
          v-for="action in config.actions"
          :key="action.name"
          :type="action.type || 'primary'"
          :icon="action.icon"
          @click="handleAction(action)"
          :style="{ marginLeft: '10px' }"
        >
          {{ action.label }}
        </el-button>
      </div>
      
      <!-- 自定义工具栏插槽 -->
      <slot name="toolbar" />
    </div>
    
    <!-- 数据表格 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      :border="config?.border !== false"
      :stripe="config?.stripe !== false"
      :size="config?.size || 'default'"
      :height="config?.height"
      :max-height="config?.maxHeight"
      :highlight-current-row="config?.highlightCurrentRow"
      :row-key="config?.rowKey || 'id'"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      class="data-table"
      v-loading="loading"
    >
      <!-- 选择列 -->
      <el-table-column
        v-if="config?.showSelection"
        type="selection"
        width="55"
        align="center"
      />
      
      <!-- 序号列 -->
      <el-table-column
        v-if="config?.showIndex"
        type="index"
        :label="config?.indexLabel || '序号'"
        width="80"
        align="center"
      />
      
      <!-- 动态列 -->
      <template v-for="column in config?.columns || []" :key="column.prop">
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :align="column.align || 'center'"
          :sortable="column.sortable"
          :filters="column.filters"
          :filter-method="column.filterMethod"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
        >
          <!-- 自定义列内容 -->
          <template #default="scope" v-if="column.render || column.slotName">
            <slot 
              v-if="column.slotName" 
              :name="column.slotName" 
              :row="scope.row" 
              :$index="scope.$index"
            />
            <component
              v-else-if="column.render"
              :is="column.render"
              :row="scope.row"
              :$index="scope.$index"
            />
            <span v-else>{{ scope.row[column.prop] }}</span>
          </template>
          
          <!-- 表头筛选 -->
          <template #header="scope" v-if="column.filterable">
            <div class="filter-header">
              <span>{{ column.label }}</span>
              <el-dropdown trigger="click" @command="(command) => handleHeaderFilter(column.prop, command)">
                <el-icon style="margin-left: 4px; cursor: pointer;">
                  <Filter />
                </el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="">全部</el-dropdown-item>
                    <el-dropdown-item 
                      v-for="option in column.filterOptions || []" 
                      :key="option.value"
                      :command="option.value"
                    >
                      {{ option.label }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </template>
      
      <!-- 操作列 -->
      <el-table-column
        v-if="config?.operationColumn"
        :label="config?.operationLabel || '操作'"
        :width="config?.operationWidth || '200'"
        align="center"
        fixed="right"
      >
        <template #default="scope">
          <slot name="operation" :row="scope.row" :$index="scope.$index" />
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-section" v-if="config?.showPagination !== false">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="config?.pageSizes || [10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElTable, ElMessage } from 'element-plus'
  import { Search, Filter } from '@element-plus/icons-vue'

  // 定义列配置接口
  interface TableColumn {
    prop: string
    label: string
    width?: number | string
    minWidth?: number | string
    align?: 'left' | 'center' | 'right'
    sortable?: boolean | 'custom'
    filterable?: boolean
    filterOptions?: Array<{ label: string; value: any }>
    filters?: Array<{ text: string; value: any }>
    filterMethod?: (value: any, row: any, column: any) => boolean
    render?: any
    slotName?: string
    showOverflowTooltip?: boolean
  }

  // 定义筛选配置接口
  interface TableFilter {
    prop: string
    label: string
    placeholder?: string
    width?: string
    options: Array<{ label: string; value: any }>
  }

  // 定义操作按钮配置接口
  interface TableAction {
    name: string
    label: string
    type?: 'primary' | 'success' | 'warning' | 'danger' | 'info'
    icon?: string
  }

  // 定义表格配置接口
  interface TableConfig {
    columns: TableColumn[]
    filters?: TableFilter[]
    actions?: TableAction[]
    showToolbar?: boolean
    showSearch?: boolean
    searchPlaceholder?: string
    searchWidth?: string
    showSelection?: boolean
    showIndex?: boolean
    indexLabel?: string
    operationColumn?: boolean
    operationLabel?: string
    operationWidth?: string | number
    showPagination?: boolean
    pageSizes?: number[]
    border?: boolean
    stripe?: boolean
    size?: 'large' | 'default' | 'small'
    height?: string | number
    maxHeight?: string | number
    highlightCurrentRow?: boolean
    rowKey?: string
  }

  // 组件Props
  interface Props {
    config: TableConfig
    data: any[]
    loading?: boolean
    total?: number
    currentPage?: number
    pageSize?: number
  }

  const props = withDefaults(defineProps<Props>(), {
    data: () => [],
    loading: false,
    total: 0,
    currentPage: 1,
    pageSize: 10
  })

  const emit = defineEmits<{
    'search': [searchText: string]
    'filter': [filters: Record<string, any>]
    'sort': [sort: { prop: string; order: 'ascending' | 'descending' }]
    'page-change': [pagination: { currentPage: number; pageSize: number }]
    'action': [action: TableAction, row?: any]
    'selection-change': [selection: any[]]
  }>()

  const tableRef = ref<InstanceType<typeof ElTable>>()
  const searchText = ref('')
  const filterValues = reactive<Record<string, any>>({})
  const headerFilters = reactive<Record<string, any>>({})
  const selectedRows = ref<any[]>([])

  // 分页配置
  const pagination = reactive({
    currentPage: props.currentPage,
    pageSize: props.pageSize,
    total: props.total
  })

  // 监听外部传入的分页变化
  watch(() => props.currentPage, (newVal) => {
    pagination.currentPage = newVal
  })

  watch(() => props.pageSize, (newVal) => {
    pagination.pageSize = newVal
  })

  watch(() => props.total, (newVal) => {
    pagination.total = newVal
  })

  // 计算表格数据（支持搜索和筛选）
  const tableData = computed(() => {
    let filteredData = [...props.data]
    
    // 搜索筛选
    if (searchText.value) {
      filteredData = filteredData.filter(row => {
        return Object.values(row).some(value => 
          String(value).toLowerCase().includes(searchText.value.toLowerCase())
        )
      })
    }
    
    // 表头筛选
    Object.keys(headerFilters).forEach(prop => {
      const filterValue = headerFilters[prop]
      if (filterValue !== '') {
        filteredData = filteredData.filter(row => row[prop] === filterValue)
      }
    })
    
    // 工具栏筛选
    Object.keys(filterValues).forEach(prop => {
      const filterValue = filterValues[prop]
      if (filterValue !== undefined && filterValue !== '') {
        filteredData = filteredData.filter(row => row[prop] === filterValue)
      }
    })
    
    return filteredData
  })

  // 搜索处理
  const handleSearch = () => {
    emit('search', searchText.value)
  }

  // 筛选处理
  const handleFilter = () => {
    emit('filter', { ...filterValues })
  }

  // 表头筛选处理
  const handleHeaderFilter = (prop: string, value: any) => {
    headerFilters[prop] = value
  }

  // 排序处理
  const handleSortChange = ({ prop, order }: any) => {
    emit('sort', { prop, order })
  }

  // 选择变化处理
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
    emit('selection-change', selection)
  }

  // 分页大小变化
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    emit('page-change', { 
      currentPage: pagination.currentPage, 
      pageSize: pagination.pageSize 
    })
  }

  // 当前页变化
  const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    emit('page-change', { 
      currentPage: pagination.currentPage, 
      pageSize: pagination.pageSize 
    })
  }

  // 操作按钮处理
  const handleAction = (action: TableAction, row?: any) => {
    emit('action', action, row)
  }

  // 暴露方法给父组件
  defineExpose({
    clearSelection: () => tableRef.value?.clearSelection(),
    toggleRowSelection: (row: any, selected?: boolean) => 
      tableRef.value?.toggleRowSelection(row, selected),
    clearFilter: () => {
      searchText.value = ''
      Object.keys(filterValues).forEach(key => {
        filterValues[key] = ''
      })
      Object.keys(headerFilters).forEach(key => {
        headerFilters[key] = ''
      })
    },
    getSelectedRows: () => selectedRows.value
  })
</script>

<style scoped lang="less">
  .data-table-container {
    width: 100%;
    
    .table-toolbar {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      flex-wrap: wrap;
      gap: 10px;
      
      .search-section {
        flex: 1;
        min-width: 300px;
      }
      
      .filter-section {
        display: flex;
        gap: 10px;
      }
      
      .action-section {
        display: flex;
        gap: 10px;
      }
    }
    
    .data-table {
      width: 100%;
      
      .filter-header {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .pagination-section {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
      padding: 10px 0;
    }
  }
  
  @media (max-width: 768px) {
    .table-toolbar {
      flex-direction: column;
      align-items: stretch;
      
      .search-section {
        min-width: auto;
      }
      
      .filter-section, .action-section {
        justify-content: flex-start;
      }
    }
  }
</style>